<script lang="ts" setup>
  import type { ConsumptionBillApi } from '#/api/spa/consumption';

  import { useVbenModal } from '@vben/common-ui';
  import { message } from 'ant-design-vue';

  import { computed, ref } from 'vue';
  import { $t } from '#/locales';
  import { useVbenForm } from '#/adapter/form';
  import { getConsumptionDetail, createConsumptionDetail, updateConsumptionDetail } from '#/api/spa/consumption';

  import { useConsumptionDetailFormSchema } from '../data';

  const emit = defineEmits(['success']);
  const formData = ref<ConsumptionBillApi.ConsumptionDetail>();
  const getTitle = computed(() => {
    return formData.value?.id
        ? $t('ui.actionTitle.edit', ['SPA消费明细'])
        : $t('ui.actionTitle.create', ['SPA消费明细']);
  });

  const [Form, formApi] = useVbenForm({
    commonConfig: {
      componentProps: {
        class: 'w-full',
      },
      formItemClass: 'col-span-2',
      labelWidth: 80,
    },
    layout: 'horizontal',
    schema: useConsumptionDetailFormSchema(),
    showDefaultActions: false
  });

  const [Modal, modalApi] = useVbenModal({
    async onConfirm() {
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }

      modalApi.lock();
      // 提交表单
      const data = (await formApi.getValues()) as ConsumptionBillApi.ConsumptionDetail;
      data.billId = formData.value?.billId;
      try {
        await (formData.value?.id ? updateConsumptionDetail(data) : createConsumptionDetail(data));
        // 关闭并提示
        await modalApi.close();
        emit('success');
        message.success( $t('ui.actionMessage.operationSuccess') );
      } finally {
        modalApi.unlock();
      }
    },
    async onOpenChange(isOpen: boolean) {
      if (!isOpen) {
        formData.value = undefined;
        return;
      }

      // 加载数据
      let data = modalApi.getData<ConsumptionBillApi.ConsumptionDetail>();
      if (!data) {
        return;
      }
      if (data.id) {
        modalApi.lock();
        try {
          data = await getConsumptionDetail(data.id);
        } finally {
          modalApi.unlock();
        }
      }
      // 设置到 values
      formData.value = data;
      await formApi.setValues(formData.value);
    },
  });
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" />
  </Modal>
</template>